<template>
  <div class="sign">
    <div class="header">
      <span class="header__title"> 账号登录</span>
    </div>
    <el-form :model="loginForm" status-icon :rules="loginRules" ref="loginFormRef" label-position="left"
      label-width="85px" class="sign__loginForm">
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="loginForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <div class="SignInForm__password">
          <el-input type="text" v-model="loginForm.password" auto-complete="off"></el-input>
        </div>
      </el-form-item>
    </el-form>
    <el-button class="sign__loginForm--loginButton" type="primary" @click="submitForm">登录</el-button>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import { unionAccountLogin } from "@/api/sign";
import { login, modifySignStatus } from "@/libs";

@Component
export default class SignIn extends Vue {
  @Ref() readonly loginFormRef: HTMLFormElement;

  loginForm = {
    // 登录类型 1-密码登录  2-验证码登录 3-扫码登录
    loginType: 1,
    // 登录账号
    phone: "18345208780",
    // phone: "18058505737",
    // 密码
    password: "admin123",
    // password: "admin123",
    // password :"123456",
    phoneCode: "",
    // 校验码凭证
    certificate: "",
    // 预扫码返回的state
    state: "",
  };

  loginRules = {
    phone: [{ required: true, validator: this.validPhone, trigger: "blur" }],
    password: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
  };

  checkRole(data) {
    if (data.shopInfoVo && data.shopInfoVo.roleInfoVo) {
      const [roleInfoVo] = data.shopInfoVo.roleInfoVo;
      if (roleInfoVo && roleInfoVo.roleCode === "0") {
        return true;
      } else {
        this.$message.warning("请使用合伙人账号登录！");
        return false;
      }
    } else {
      return true;
    }
  }

  async submitForm() {
    try {
      await this.loginFormRef.validate();
      const form = {
        loginType: this.loginForm.loginType,
        certificate: this.loginForm.certificate,
        phone: this.loginForm.phone,
        password: this.loginForm.password,
        state: this.loginForm.state,
      };
      const response = await unionAccountLogin(form);
      const { data, code } = response;
      if (code === 200) {
        this.checkRole(data);
        modifySignStatus(data.token, data);
        login(data.token, data);
        this.$router.push("/overview");
      }
    } catch (e) {
      console.log(e);
      this.$message.error(e);
    }
  }

  validPhone(rule, value, callback) {
    if (!value) {
      callback(new Error("请输入电话号码"));
    } else if (!this.isvalidPhone(value)) {
      callback(new Error("请输入正确的11位手机号码"));
    } else {
      callback();
    }
  }

  isvalidPhone(str) {
    const reg =  /^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[1,8,9])\d{8}$/;
    return reg.test(str);
  }
}
</script>
